package com.jh.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jh.annotation.AutoFill;
import com.jh.dto.OderPageQueryDTO;
import com.jh.dto.SettlementDataDTO;
import com.jh.entity.*;
import com.jh.enumeration.OperationType;
import com.jh.mapper.OrderDetailMapper;
import com.jh.mapper.OrderMapper;
import com.jh.mapper.ProductDetailMapper;
import com.jh.result.PageResult;
import com.jh.service.SettlementService;
import com.jh.vo.OderPageQueryVO;
import com.jh.vo.OrderDetailDTO;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.List;

@Service
public class SettlementServiceImpl implements SettlementService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ProductDetailMapper productDetailMapper;
    /**
     * 工作台提交订单
     * @param settlementDataDTO
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void submitSettlement(SettlementDataDTO settlementDataDTO) {
        if (settlementDataDTO == null || settlementDataDTO.getItems() == null || settlementDataDTO.getItems().isEmpty()) {
            throw new IllegalArgumentException("结算数据或商品条目不能为空");
        }

        try {
            // 1. 创建订单
          Order order = Order.builder()
                    .orderCode(generateOrderCode("8888")) // 生成符合规范的订单编码(自定义方法)
                    .totalActualPrice(settlementDataDTO.getTotalActualPrice())
                    .totalRetailPrice(settlementDataDTO.getTotalRetailPrice())
                    .remark(settlementDataDTO.getRemark())
                    .total(settlementDataDTO.getTotal())
                    .build();

            orderMapper.insert(order);

            // 2. 获取订单ID
            Long orderId = orderMapper.getOrderIdByOrderCode(order.getOrderCode());
            if (orderId == null) {
                throw new RuntimeException("订单创建失败");
            }

            // 3. 更新产品详情表中的订单ID和状态
            for (SettlementItem item : settlementDataDTO.getItems()) {
                ProductDetail productDetail = productDetailMapper.selectById(item.getPdId());

                if (productDetail != null && productDetail.getStatus() == 1) {
                    productDetail.setStatus(0);
                    productDetailMapper.updateById(productDetail);
                    OrderDetail orderDetail=OrderDetail.builder().
                            orderId(orderId).
                            productDetailId(item.getPdId()).
                            actualPrice(item.getActualPrice()).
                            build();

                    orderDetailMapper.insert(orderDetail);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("订单提交失败", e);
        }
    }

    /**
     * 订单分页查询
     * @return
     */
    public PageResult page(OderPageQueryDTO oderPageQueryDTO) {
        //执行查询
        Page<OderPageQueryVO> page=new Page<>(oderPageQueryDTO.getPage(),oderPageQueryDTO.getPageSize());
        page=orderMapper.page(page,oderPageQueryDTO);
        long total = page.getTotal();
        List<OderPageQueryVO> records = page.getRecords();
        return new PageResult(total,records);
    }

    /**
     * 根据id查询订单详情
     *
     * @param orderId
     * @return
     */
    public List<OrderDetailDTO> getOrderDetails(Long orderId) {
        List<OrderDetailDTO> result = orderDetailMapper.getOrderDetailsByOrderId(orderId);
        if (result == null) {
            throw new RuntimeException("订单不存在,数据错误");
        }
        return result;
    }

    /**
     * 根据订单ID删除订单
     *
     * @param orderId
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在,数据错误");
        }
        // 1.更新产品详情
        productDetailMapper.updateByOrderId(orderId);
        // 2. 更新产品详情表中的订单 ID 和状态
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId, orderId);
        orderDetailMapper.delete(wrapper);
        Long id=orderId;
        orderMapper.deleteById(id);
    }

    /**
     * 生成符合服装店规范的订单编码
     *
     * @param shopCode 店铺编号
     * @return 订单编码
     */
    private String generateOrderCode(String shopCode) {
        // 1. 获取当前日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = dateFormat.format(new Date());

        // 2. 生成随机数（4位）
        int randomNum = (int) (Math.random() * 9000) + 1000;

        // 5. 拼接订单编码
        return String.format("%s-%s-%04d", shopCode, dateStr, randomNum);
    }
}

